package com.example.zhilongzhang.constructionpayapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.zhilongzhang.constructionpayapp.R;
import com.example.zhilongzhang.constructionpayapp.base.BaseActivity;
import com.example.zhilongzhang.constructionpayapp.base.ToastManager;
import com.example.zhilongzhang.constructionpayapp.bean.ImgMainBean;
import com.example.zhilongzhang.constructionpayapp.bean.LoginBean;
import com.example.zhilongzhang.constructionpayapp.bean.UserInfoBean;
import com.example.zhilongzhang.constructionpayapp.dialog.WaitDialog;
import com.example.zhilongzhang.constructionpayapp.http.HttpMethod;
import com.example.zhilongzhang.constructionpayapp.util.SpUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends BaseActivity {
    ImageView ivCancelAccoout,ivCancelPass;
    EditText edAccout,edPass;
    WaitDialog mDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        edAccout=findViewById(R.id.ed_account);
        ivCancelAccoout = findViewById(R.id.cancel_accoout);
        edPass=findViewById(R.id.ed_pass);
        ivCancelPass = findViewById(R.id.cancel_pass);
        initData();

        // 显隐(用户名)
        edAccout.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    ivCancelAccoout.setVisibility(View.VISIBLE);
                } else {
                    ivCancelAccoout.setVisibility(View.INVISIBLE);
                }
            }
        });

        // 显隐(密码)
        edPass.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    ivCancelPass.setVisibility(View.VISIBLE);
                } else {
                    ivCancelPass.setVisibility(View.INVISIBLE);
                }
            }
        });

        // 用户名全部删除
        ivCancelAccoout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edAccout.setText("");
            }
        });

        // 密码全部删除
        ivCancelPass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edPass.setText("");
            }
        });


    }
    private void initData(){
        findViewById(R.id.tv_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edAccout.getText())){
                    ToastManager.getInstance(LoginActivity.this).showToast("请输入账号");
                   return;
                }
                if (TextUtils.isEmpty(edPass.getText())){
                    ToastManager.getInstance(LoginActivity.this).showToast("请输入密码");
                    return;
                }
                mDialog = new WaitDialog(LoginActivity.this);
                mDialog.show();
                login(edAccout.getText().toString(),edPass.getText().toString());
            }
        });
        findViewById(R.id.tv_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(LoginActivity.this,RigisterActivity.class);
                startActivity(intent);
            }
        });
        findViewById(R.id.cancel_accoout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edAccout.setText("");
            }
        });
        findViewById(R.id.cancel_pass).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edPass.setText("");
            }
        });
    }
    private void login(final String username, final String password) {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .add("os",  "android")
                .build();
        Request request = new okhttp3.Request.Builder()
                .url(HttpMethod.BaseUrl2+"login")
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mDialog.dismiss();
                LoginActivity.this.runOnUiThread(new TimerTask() {
                    @Override
                    public void run() {
                        ToastManager.getInstance(LoginActivity.this).showToast("网络异常");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseStr=response.body().string();
                LoginBean bean = new Gson().fromJson(responseStr, LoginBean.class);
                mDialog.dismiss();
                if (bean.getCode()==0){
                    SpUtil.setUserName(username);
                    SpUtil.setPassword(password);
                    SpUtil.setToken(bean.getData().getAccess_token());
                    getData();
                }else {
                    LoginActivity.this.runOnUiThread(new TimerTask() {
                        @Override
                        public void run() {
                            ToastManager.getInstance(LoginActivity.this).showToast("用户名或密码错误");
                        }
                    });

                }


            }
        });
    }
    private void getData() {
        HttpMethod.security(new StringCallback() {
            @Override
            public void onError(com.squareup.okhttp.Request request, Exception e) {
                ToastManager.getInstance(LoginActivity.this).showToast("网络异常");
            }

            @Override
            public void onResponse(String response) {
                if (response == null) {
                    Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                    return;
                }
                UserInfoBean bean = new Gson().fromJson(response, UserInfoBean.class);
                if (bean.getDept() != null) {
                    SpUtil.setName(bean.getRealName());
                    SpUtil.setShopName(bean.getDept().getDeptName());
                    SpUtil.setShopSearUrl(String.valueOf(bean.getDept().getDepReqUrl()));
                    SpUtil.setShopAddUrl(String.valueOf(bean.getDept().getDepSaveUrl()));
                    SpUtil.setQRImgUrl(String.valueOf(bean.getDept().getQrReqUrl()));
                    SpUtil.setQRPayUrl(String.valueOf(bean.getDept().getQrSaveUrl()));
                    SpUtil.setShopId(String.valueOf(bean.getDept().getId()));
                    SpUtil.setType(String.valueOf(bean.getDept().getDeptType()));
                    SpUtil.setGSDM(bean.getDept().getCompanyCode());
                }
                if (bean.getTel() != null) {
                    SpUtil.setTel(bean.getTel());
                }
                SpUtil.setUserId(String.valueOf(bean.getId()));
                getFiles(String.valueOf(bean.getDept().getId()));
            }
        });
    }
    String imgList="";
    private void getFiles(String depId) {
        HttpMethod.getFiles(depId,new StringCallback() {
            @Override
            public void onError(com.squareup.okhttp.Request request, Exception e) {
                mDialog.dismiss();
                Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onResponse(String response) {
                mDialog.dismiss();
                if (response == null) {
                    Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                    return;
                }
                ImgMainBean bean = new Gson().fromJson(response, ImgMainBean.class);
                if (bean.getData()!=null){
                    for (int i = 0; i < bean.getData().size(); i++) {
                        if (i==0){
                            imgList=bean.getData().get(i).getUrl();
                        }else {
                            imgList=imgList+","+bean.getData().get(i).getUrl();
                        }

                    }
                    SpUtil.setListImg(imgList);
                  /*  Gson gson=new Gson();
                    SpUtil.setListImg(gson.toJson(imgList));*/
                }
                Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

}
